package com.example.myapplication.audio;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.text.format.DateFormat;
import android.view.Gravity;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.PopupMenu;

import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.R;
import com.example.myapplication.bean.AudioBean;
import com.example.myapplication.databinding.ActivityAudioListBinding;
import com.example.myapplication.utils.AudioInfoDialog;
import com.example.myapplication.utils.AudioInfoUtils;
import com.example.myapplication.utils.Contains;
import com.example.myapplication.utils.DialogUtils;
import com.example.myapplication.utils.RenameDialog;
import com.example.myapplication.utils.StorageUtils;


import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

public class AudioListActivity extends AppCompatActivity {
    private ActivityAudioListBinding binding;
    private List<AudioBean> mData;
    private AudioListAdapter adapter;
    private AudioService audioService;


    /**
     *
     */
    ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            audioService = ((AudioService.AudioBinder) service).getService();
            audioService.setOnPlayChangedListener(playChangedListener);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    /**
     * 程序的入口
     *
     * @param savedInstanceState If the activity is being re-initialized after
     *                           previously being shut down then this Bundle contains the data it most
     *                           recently supplied in {@link #onSaveInstanceState}.  <b><i>Note: Otherwise it is null.</i></b>
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityAudioListBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        //绑定AudioService类
        Intent intent = new Intent(this, AudioService.class);
        boolean b = bindService(intent, connection, BIND_AUTO_CREATE);
        System.out.println("bind:" + b);

        //为listview设置数据源和adapter
        mData = new ArrayList<>();
        adapter = new AudioListAdapter(this, mData);
        binding.audioLv.setAdapter(adapter);

        //获取数据
        try {
            getData();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //保存数据到容器中
        Contains.setMyAudioList(mData);

        //设置监听事件
        setEvent();
    }

    /**
     * 设置监听事件
     * 包括监听各种按钮点击事件
     */
    private void setEvent() {
        adapter.setOnItemPlayClickListener(itemPlayClickListener);
        binding.audioLv.setOnItemLongClickListener(longClickListener);

        binding.audioIb.setOnClickListener(onClickListener1);
//        View.OnClickListener onClickListener2;
        binding.audioListStop.setOnClickListener(onClickListener2);
        binding.audioListDelete.setOnClickListener(onClickListener3);
    }


    /**
     * 定时器
     */
    private int mElapsedTime = 0;
    private Timer mTimer;

    private void startTimer() {
        mTimer = new Timer();
        mTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                if (!isPaused) {
                    mElapsedTime++;
                    updateTimerView();
                }
            }
        }, 0, 1000);
    }

    private void updateTimerView() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                int hours = mElapsedTime / 3600;
                int minutes = (mElapsedTime % 3600) / 60;
                int seconds = mElapsedTime % 60;
                @SuppressLint("DefaultLocale")
                String time = String.format("%02d:%02d:%02d", hours, minutes, seconds);
                binding.audioListTime.setText(time);
            }
        });
    }

    @SuppressLint("SetTextI18n")
    void stopRecord() {
        mediaRecorder.stop();
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
            mElapsedTime = 0;
        }
        isRecording = false;
        isPaused = false;
        binding.audioIb.setImageResource(R.drawable.ic_mic);
        binding.state.setText("已停止");
        binding.audioListTime.setText("00:00:00");
    }


    private boolean isRecording = false;
    private boolean isPaused = false;
    /**
     * 点击监听器，开始录音按钮
     */
    MediaRecorder mediaRecorder = null;
    String fileName;
    /**
     * 录音按钮
     */
    View.OnClickListener onClickListener1 = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //点击录音按钮，关闭当前播放，开始录音
            audioService.closeMusic();
            for (AudioBean ab :
                    mData) {
                ab.setPaused(false);
                ab.setPlaying(false);
            }

            /**
             *
             */
            if (!isRecording && !isPaused) {
                startRecording();
                startTimer();
                binding.audioIb.setImageResource(R.drawable.ic_pause_white);
                binding.state.setText("正在录音");
                isRecording = true;
            } else if (isRecording && !isPaused) {
                pauseRecording();
                binding.audioIb.setImageResource(R.drawable.ic_play_arrow_white);
                binding.state.setText("已暂停");

                isRecording = false;
                isPaused = true;
            } else {
                continueRecording();
                binding.state.setText("正在录音");

                binding.audioIb.setImageResource(R.drawable.ic_pause_white);
                isRecording = true;
                isPaused = false;
            }
        }

    };
    /**
     * 停止按钮
     */
    View.OnClickListener onClickListener2 = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if ((isPaused ^ isRecording) && mediaRecorder != null) {
                stopRecord();
                //刷新界面
                try {
                    getData();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
//            mediaRecorder.release();
                adapter.notifyDataSetChanged();
            }
        }
    };

    /**
     * 删除按钮
     */
    View.OnClickListener onClickListener3 = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if ((isPaused ^ isRecording) && mediaRecorder != null) {
                stopRecord();
                boolean b = StorageUtils.deleteFileInAppDir(fileName);
                System.out.println("删除刚才录制的文件：" + b + Contains.PATH_SUB_RECORD + "/" + fileName);
                adapter.notifyDataSetChanged();
            }
        }
    };

    private void continueRecording() {
        if (mediaRecorder != null) {
            mediaRecorder.resume();
        }
    }

    private void pauseRecording() {
        if (mediaRecorder != null) {
            mediaRecorder.pause();
        }
    }

    private void startRecording() {
        if (mediaRecorder == null)
            mediaRecorder = new MediaRecorder();
        //
        // 设置音频源
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);

        // 设置输出格式
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        // 设置音频编码器
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        // 设置录音文件保存路径
        fileName = DateFormat.format("yyyyMMdd_HHmmss", Calendar.getInstance(Locale.CHINA)) + ".m4a";
        mediaRecorder.setOutputFile(Contains.PATH_SUB_RECORD + "/" + fileName);
//            new AudioBean()
        try {
            // 准备录音
            mediaRecorder.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }

//            System.out.println(Contains.PATH_APP_DIR +fileName);
        // 开始录音
        mediaRecorder.start();
//计时开始
//            mCountDownTimer.start();
    }

    private CountDownTimer mCountDownTimer = new CountDownTimer(5000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            // 更新录音时间
            System.out.println("recording..." + Contains.PATH_SUB_RECORD + File.separator + fileName);
        }

        @Override
        public void onFinish() {
            // 停止录音
            mediaRecorder.stop();
            try {
                getData();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
//            mediaRecorder.release();
            adapter.notifyDataSetChanged();

        }
    };


    /**
     * 方法重写：点击返回，退出程序
     */
    @Override
    public void onBackPressed() {
        finishAffinity();
    }

    /**
     * 接口实现
     */
    AudioService.OnPlayChangedListener playChangedListener = new AudioService.OnPlayChangedListener() {
        @Override
        public void playChange(int position) {
            adapter.notifyDataSetChanged();
        }
    };


    /**
     * 方法重写：destroy方法，解绑connection
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
//        mediaRecorder.reset();
        if (mediaRecorder != null) {
            mediaRecorder.release();
        }
        unbindService(connection);
    }

    /**
     * 点击播放/暂停监听器，AudioListAdapter接口实现
     */
    AudioListAdapter.OnItemPlayClickListener itemPlayClickListener = new AudioListAdapter.OnItemPlayClickListener() {
        @Override
        public void onItemPlayClick(AudioListAdapter adapter, View convertView, View playView, int position) throws IOException {
            for (int i = 0; i < mData.size(); i++) {
                System.out.println("执行");
                if (i == position) {
                    continue;
                }
                mData.get(i).setPlaying(false);
                mData.get(i).setPaused(false);

//                audioBean.setPlaying(false);
            }
            boolean playing = mData.get(position).isPlaying();
            mData.get(position).setPlaying(!playing);

            adapter.notifyDataSetChanged();
            audioService.cutMusicOrPause(position);
        }
    };

    /**
     * 列表长按监听器
     */
    AdapterView.OnItemLongClickListener longClickListener = new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            showPopMenu(view, position);
            mData.get(position).setPlaying(false);
            mData.get(position).setPaused(false);
            audioService.closeMusic();//当长按时停止播放,防止异常
            return false;
        }
    };

    /**
     * 长安每一项弹出菜单
     *
     * @param view     当前视图
     * @param position 长按的位置
     */
    private void showPopMenu(View view, int position) {

        PopupMenu popupMenu = new PopupMenu(this, view, Gravity.RIGHT);
        MenuInflater menuInflater = popupMenu.getMenuInflater();
        menuInflater.inflate(R.menu.audio_menu, popupMenu.getMenu());
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_info:
                        showInfo(position);
                        break;
                    case R.id.menu_del:
                        deleteMyFile(position);
                        break;
                    case R.id.menu_rename:
                        renameDialog(position);
                        break;
                }
                return false;
            }
        });
        popupMenu.show();//显示菜单
    }

    /**
     * 显示文件详情对话框
     *
     * @param position 当前文件位置
     */
    private void showInfo(int position) {
        AudioBean audioBean = mData.get(position);
        AudioInfoDialog audioInfoDialog = new AudioInfoDialog(this);
        audioInfoDialog.show();
        audioInfoDialog.setDialogWidth();
        audioInfoDialog.setInfo(audioBean);
        audioInfoDialog.setCanceledOnTouchOutside(true);
    }

    /**
     * 重命名对话框
     *
     * @param position 位置
     */
    private void renameDialog(int position) {
        //
        AudioBean audioBean = mData.get(position);
        String title = audioBean.getTitle();
        RenameDialog dialog = new RenameDialog(this);
        dialog.show();
        dialog.setDialogWidth();
        dialog.setTipText(title);
        dialog.setOnEnsureListener(new RenameDialog.OnEnsureListener() {
            @Override
            public void onEnsure(String msg) {
                renameByPosition(msg, position);
            }
        });
    }

    /**
     * 对于指定位置的文件重命名
     *
     * @param msg
     * @param position
     */
    private void renameByPosition(String msg, int position) {
        AudioBean audioBean = mData.get(position);
        if (audioBean.getTitle().equals(msg)) {
            return;
        }
        String path = audioBean.getPath();
        String fileSuffix = audioBean.getFileSuffix();
        File srcFile = new File(path);

        String destPath = srcFile.getParent() + File.separator + msg + fileSuffix;

        boolean b = srcFile.renameTo(new File(destPath));

        System.out.println(b ? "重命名成功" : "重命名失败");
        if (b) {
            audioBean.setTitle(msg);
            audioBean.setPath(destPath);
        }
        adapter.notifyDataSetChanged();
    }

    /**
     * 删除文件
     *
     * @param position
     */
    private void deleteMyFile(int position) {
        AudioBean audioBean = mData.get(position);
        String title = audioBean.getTitle();
        String path = audioBean.getPath();
        DialogUtils.showNormalDialog(this, "提示信息", "删除确认？",
                "确定", new DialogUtils.OnLeftClickListener() {
                    @Override
                    public void onLeftClick() {
                        File file = new File(path);
                        File absoluteFile = file.getAbsoluteFile();
                        absoluteFile.delete();
                        System.out.println(audioBean);
                        mData.remove(audioBean);
                        adapter.notifyDataSetChanged();
                    }
                }, "取消", null);
    }

    /**
     * 获取数据添加到mData中，刷新
     *
     * @throws IOException
     */
    private void getData() throws IOException {
        mData.clear();
        System.out.println(Contains.PATH_SUB_RECORD + "\n" + Contains.PATH_APP_DIR);
        File file = new File(Contains.PATH_SUB_RECORD);
        File[] listFiles = file.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                if (new File(dir, name).isDirectory()) return false;//如果存在文件夹，不要
                if (name.endsWith(".mp3") || name.endsWith(".m4a")) {//过滤音频文件
//                    System.out.println("tru");
                    return true;
                }
                return false;
            }
        });
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        AudioInfoUtils audioInfoUtils = AudioInfoUtils.getInstance();
        //遍历数组里的文件，依次得到文件信息
//        System.out.println(listFiles.length);
        if (listFiles !=null)
            for (int i = 0; i < listFiles.length; i++) {
                System.out.println(i);
                File audioFile = listFiles[i];//取出每一个音频文件
                String fName = audioFile.getName();
                String title = fName.substring(0, fName.lastIndexOf("."));
                String suffix = fName.substring(fName.lastIndexOf("."));

                //最后编辑时间,转化格式
                long lastModified = audioFile.lastModified();
                String time = dateFormat.format(lastModified);
                //获取文件大小
                long fileSize = audioFile.length();
                String audioPath = audioFile.getAbsolutePath();
                long duration = audioInfoUtils.getAudioFileDuration(audioPath);
                String formattedDuration = audioInfoUtils.getAudioFileFormattedDuration("HH:mm:ss", duration);
                AudioBean audioBean = new AudioBean(i + "", title, time, formattedDuration, audioPath,
                        duration, lastModified, suffix, fileSize);
                System.out.println(audioBean);
                mData.add(audioBean);
            }
        audioInfoUtils.releaseRetriever();//释放媒体资源对象
        //将集合中的元素重新排序
        mData.sort(new Comparator<AudioBean>() {
            @Override
            public int compare(AudioBean o1, AudioBean o2) {
                if (o1.getLastModified() < o2.getLastModified()) {
                    return 1;
                } else if (o1.getLastModified() == o2.getLastModified()) {
                    return 0;
                }
                return -1;
            }
        });
        adapter.notifyDataSetChanged();//通知更改
    }

}
